<?php
set_time_limit(0); 
ini_set('memory_limit','256M');
require_once("./config.php");
header("Content-Type: text/html;charset=utf-8");
function test_post($url,$post_data)
{
	//初始化
    $ch = curl_init();
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
	curl_setopt($ch, CURLOPT_TIMEOUT, 5);
	$resultJson = curl_exec($ch);
	$curlInfo = curl_getinfo($ch);
	$errNo = curl_errno($ch);
	curl_close($ch);
    //显示获得的数据
	return $resultJson;
    //var_dump($resultJson,$curlInfo,$errNo);
}

function parse($content){

	$table_data = preg_match_all('/<tbody[^>]*>(.*?) <\/tbody>/si',$content,$match);
	$table_data = $match[0][0];
	$tr_data = explode("<tr>",$table_data);
	$data =array();
	for($i=1;$i<count($tr_data);$i++){
		$data[$i] = explode('</td>',$tr_data[$i]);
		for($j = 0;$j<count($data[$i]);$j++){
			$data[$i][$j] = preg_replace('/\s(?=\s)/','',trim(strip_tags($data[$i][$j])));
		}
		array_pop($data[$i]);
	}
	return $data;
}


$url="https://yz.chsi.com.cn/zsml/queryAction.do";

$dir = "D:/workdata/test/chsi/se/";
$outdir = "D:/workdata/test/chsi/rs/";
$tempcity = "82";

$filename = $dir.$tempcity.".txt";
$handle  = fopen ($filename, "r");

$i=0;
while (!feof ($handle)){
	$buffer  = fgets($handle);
	if(strlen($buffer) < 10){
		break;
	}
	$content = json_decode($buffer,true);
	$html = test_post($url,$content);
	$school = parse($html);
	if(count($school)>0){
		$str="";
		foreach($school as $key=>$val){
			$str.=json_encode($val)."\n";

		}
		$path = $outdir."/".$tempcity;
		if(!is_dir($path)){
			mkdir($path);
		}
		$filename = $path."/".$content['ssdm']."_".$content['mldm']."_".$content['yjxkdm']."_".iconv("UTF-8","gbk",$content['zymc'])."_".$content['xxfs'].".txt";
		$filename2 = $path."/".$content['ssdm']."_".$content['mldm']."_".$content['yjxkdm']."_".$content['zymc']."_".$content['xxfs'].".txt";

		$fh=fopen($filename, "w+");
		fwrite($fh, $str);    // 输出：6
		fclose($fh);
		echo $filename2."<br>";
	}
	//var_dump(parse($html));

	//break;
}
//var_dump($rs);


// 专业查询
$url="https://yz.chsi.com.cn/zsml/queryAction.do";
$data['ssdm'] = 12;
$data['dwmc'] = '';
$data['mldm'] = 'zyxw';
$data['mlmc'] = '';
$data['yjxkdm'] = '0252';
$data['zymc'] = '应用统计';
$data['xxfs'] = '';

/*理论查询

ssdm: 11
dwmc: 
mldm: 02
mlmc: 
yjxkdm: 0201
zymc: 理论经济学
xxfs: 
*/


//$html = test_post($url,$data);
//print_r(json_decode($ssdm,true));








?>